﻿@page "/profile"
@using AntDesign
@inject MessageService Message
@inject IHttpClientFactory Http
@layout MainLayout
@using lcwb.Shared.Model


<PageHeader Title="用户主页" Subtitle="管理您的个人信息" />
<div>
    <Card>
        <Form Model="@userProfile" Layout="@FormLayout.Vertical">
            <!-- 新增头像区域 -->
            <FormItem Label="头像">
                @if (isEditing)
                {
                    <!-- 需要替换为真实API Upload Action-->
                    <Upload Action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            Accept=".jpg,.jpeg,.png"
                            Multiple="false"
                            ShowUploadList="false"
                            ShowDownloadIcon="true"
                            ShowPreviewIcon="true"
                            ShowRemoveIcon="true"
                            BeforeUpload="@BeforeUpload"
                            OnSingleCompleted="@OnSingleCompleted"
                            ListType="UploadListType.PictureCard">
                        <Button Icon="upload">选择头像</Button>
                    </Upload>
                }
                else
                {
                    <Avatar Size="@("64")" Src="@userProfile.AvatarUrl" />
                }
            </FormItem>
            <FormItem Label="姓名">
                @if (isEditing)
                {
                    <Input @bind-Value="userProfile.Name" />
                }
                else
                {
                    <span>@userProfile.Name</span>
                }
            </FormItem>

            <FormItem Label="邮箱">
                @if (isEditing)
                {
                    <Input @bind-Value="userProfile.Email" />
                }
                else
                {
                    <span>@userProfile.Email</span>
                }
            </FormItem>

            <FormItem Label="电话">
                @if (isEditing)
                {
                    <Input @bind-Value="userProfile.PhoneNumber" />
                }
                else
                {
                    <span>@userProfile.PhoneNumber</span>
                }
            </FormItem>

            <FormItem Label="地址">
                @if (isEditing)
                {
                    <Input @bind-Value="userProfile.Address" />
                }
                else
                {
                    <span>@userProfile.Address</span>
                }
            </FormItem>

            <FormItem>
                @if (isEditing)
                {
                    <Button Type="ButtonType.Primary" OnClick="SaveProfile" Loading="@isSaving">保存</Button>
                    <Button OnClick="CancelEdit">取消</Button>
                }
                else
                {
                    <Button Type="ButtonType.Primary" OnClick="() => isEditing = true">修改</Button>
                }
            </FormItem>
        </Form>
    </Card>
</div>


@code {

    /*
         *
         * 添加错误处理
         * 实现真实的API调用
         * 添加权限验证
         * 扩展更多的用户信息字段
         * 添加密码修改等其他功能模块
         * */
    private UserProfileModel userProfile = new();
    // When edit it save one
    private UserProfileModel originalProfile = new();
    private bool isEditing = false;
    private bool isSaving = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadUserProfile();
    }

    private async Task LoadUserProfile()
    {
        // 模拟API调用
        userProfile = new()
            {
                Name = "王申",
                Email = "wangshen7562@henu.edu.cn",
                Address = "河南省郑州市郑东新区明理路北段379号",
                PhoneNumber = "13303862697",
                AvatarUrl = "https://th.bing.com/th/id/R.46efb6b132359fffe2b27a2afad41aec?rik=aYpOdA9ytO1TDg&riu=http%3a%2f%2fwww.pngall.com%2fwp-content%2fuploads%2f7%2fDoge-PNG-Free-Download.png&ehk=3OXJjsWZIj5SykzQ7dqNbSsMWPE2XMDno1QoG5qvUpM%3d&risl=&pid=ImgRaw&r=0"  // 默认头像
            };
        //userProfile = await Http.GetFromJsonAsync<UserProfileModel>("api/user/profile");

        // give
        originalProfile = CloneProfile(userProfile);
    }

    private bool BeforeUpload(UploadFileItem file)
    {
        // 这里可以添加文件格式/大小验证
        // 示例验证：
        const int maxSize = 2 * 1024 * 1024; // 2MB
        var validTypes = new[] { "image/jpeg", "image/png" };

        if (file.Size > maxSize)
        {
            Message.Error("文件大小不能超过2MB");
            return false;
        }

        if (!validTypes.Contains(file.Type))
        {
            Message.Error("只支持JPG/PNG格式");
            return false;
        }

        return true; // 允许上传
    }

    private async void OnSingleCompleted(UploadInfo fileinfo)
    {
        // 这里需要处理上传成功后的响应
        // 假设API返回图片URL：
        userProfile.AvatarUrl = fileinfo.File.Url;
        await Message.Success("头像上传成功");
        StateHasChanged();
    }


    private UserProfileModel CloneProfile(UserProfileModel profile)
    {
        return new UserProfileModel
            {
                Name = profile.Name,
                Email = profile.Email,
                PhoneNumber = profile.PhoneNumber,
                Address = profile.Address
            };
    }

    private async Task SaveProfile()
    {
        if (!await ValidateForm())
        {
            return;
        }

        isSaving = true;
        try
        {
            // 模拟API保存

            //await Http.PutAsJsonAsync("api/user/profile", userProfile);
            originalProfile = CloneProfile(userProfile);
            
            isEditing = false;
            await Message.Success("保存成功");
        }
        finally
        {
            isSaving = false;
        }
    }

    private Task<bool> ValidateForm()
    {
        // 这里可以添加自定义验证逻辑
        // originalPorfike
        return Task.FromResult(true);
    }

    private void CancelEdit()
    {
        // rollback
        userProfile = CloneProfile(originalProfile);
        isEditing = false;
    }
}